//src/client/pages/index/index.js
//index 组件
import React from 'react';
import { Helmet } from 'react-helmet';
import './index.scss';

//组件
export default class Index extends React.Component {
  constructor(props) {
    super(props);
    let initialData = null;//初始化数据
    if(__SERVER__){//如果是当然是服务端执行
      initialData = props.staticContext/** ←由react-ssr.js里的StaticRouter组件赋予的,就是StaticRouter接受的context属性*/.initialData||{};
    }else{
      //客户端渲染
      initialData = props.initialData || {};
    }
    this.state = {
      ...initialData
      ,count:0
      ,aaa:222
    };
  }

  handlerClick() {
    alert('一起来玩 react 服务端渲染~~');
  }

  static async getInitialProps() {
    console.log('fetch data index');
    //模拟数据请求方法
    //...

    return {
      page: {
        tdk: {
          title: '首页 - react ssr',
          keywords: '前端技术江湖',
          description: '描述'
        }
      }
    };
  }

  componentDidMount() {
    if (!this.state.fetchData) {
      //如果没有数据，则进行数据请求
      Index.getInitialProps().then(res => {
        this.setState({
          fetchData: res.fetchData || [],
          page:res.page
        });

        // document.title = res.page.tdk.title;
      })
    }

    // if (this.state.page && this.state.page.tdk) {
    //   document.title = this.state.page.tdk.title;
    // }
  }

  render() {
    console.log('this.state:',this.state)
    const {tdk={}} = this.state.page || {};
    return (
      <div className="page-index-box">
        <Helmet>
          <title>{tdk.title}</title>
          <meta name="description" content={tdk.description}/>
          <meta name="keywords" content={tdk.keywords}/>
        </Helmet>
        123首页
        {this.state.count}
        <button onClick={()=>this.setState({count: this.state.count + 1})}>+</button>
        emmm {this.state.aaa}
      </div>
    )
  }
};
